

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:shop/pages/home/home_page.dart';
import 'package:shop/pages/login/login_view.dart';
import 'package:shop/pages/tap_page.dart';
import 'package:shop/pages/web_view_page.dart';

import '../utils/token_utils.dart';


class GlobalNavigatorObserver extends NavigatorObserver {
  // 路由跳转完成时触发
  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    // 记录跳转日志（如当前页面、上一页面）
    print('路由跳转：${previousRoute?.settings.name} → ${route.settings.name}');
    // 埋点统计：记录页面访问量
    _trackPageView(route.settings.name);
  }

  // 路由弹出时触发（如返回上一页）
  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    print('路由返回：${route.settings.name} → ${previousRoute?.settings.name}');
  }

  // 页面访问统计
  void _trackPageView(String? pageName) {
    if (pageName != null) {
      // 调用统计 SDK 上报
      // Analytics.trackEvent('page_view', {'page': pageName});
    }
  }
}
class AppRouter{
  // 私有构造函数（防止外部实例化）
  AppRouter._();

  // 单例实例
  static final AppRouter _instance = AppRouter._();

  // 工厂方法获取单例
  factory AppRouter() => _instance;

  // GoRouter 实例（核心）
  late final GoRouter router = GoRouter(
    observers: [GlobalNavigatorObserver()],
    // 全局路由跳转前拦截
    redirect: (context, state) async {
      // 1. 检查是否有 token（从本地存储读取）
      final hasToken = await TokenUtils.getToken() != null;
      // 2. 当前要跳转的路径
      final targetPath =Uri.encodeComponent(state.matchedLocation) ;

      // 3. 拦截逻辑：未登录且目标不是登录页 → 跳登录页
      if (!hasToken && targetPath != '/login') {
        return '/login?redirect=$targetPath'; // 携带原路径，方便登录后返回
      }
      // 允许跳转
      return null;
    },
    routes: <RouteBase>[

      GoRoute(

        path: "/",
        builder: (BuildContext context, GoRouterState state) {
          return const TabPage();
        },
        routes: <RouteBase>[
          GoRoute(
            path: 'web_view_page/:uri',
            builder: (BuildContext context, GoRouterState state) {
              // 从路径参数中获取 title（注意：子路由路径参数需在父路由中声明或通过查询参数传递）
              // 这里修正：子路由 path 若需要参数，应写成 'web_view_page/:title
              final String uri = state.pathParameters["uri"]!;
              return WebViewPage(url: uri);
            },
          ),
        ],
      ),
      GoRoute(path:"/login",
          builder: (BuildContext context,GoRouterState state){
            final String redirect = state.uri.queryParameters["redirect"]??"";
            return LoginViewPage(redirect: redirect,);
          }
      ),
    ],

  );
}